/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import model.Course;
import model.StudentCourseOperation;
import model.Student;
import model.UserService;

/**
 *
 * @author 10515
 */
public class StudentInterface extends javax.swing.JFrame {

    /**
     * Creates new form StudentService
     */
    public StudentInterface() {
        initComponents();
        final String filePath = "./data/Courses.txt";
        DefaultTableModel model =(DefaultTableModel) jTable1.getModel();
        try (FileInputStream fis = new FileInputStream(filePath);
             InputStreamReader isr = new InputStreamReader(fis);
             BufferedReader br = new BufferedReader(isr)) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] strs = line.split("\\s+");
                Object[] o={strs[0],strs[1],Integer.parseInt(strs[2]),Integer.parseInt(strs[3])};
                model.addRow(o);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        SelectCourse = new javax.swing.JButton();
        checkSelectedCourse = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("公选课选课系统");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                " 课程名称", "任课教师", "已选人数", "课程限制人数", "是否选择"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setResizable(false);
            jTable1.getColumnModel().getColumn(1).setResizable(false);
            jTable1.getColumnModel().getColumn(2).setResizable(false);
            jTable1.getColumnModel().getColumn(3).setResizable(false);
            jTable1.getColumnModel().getColumn(4).setResizable(false);
        }

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1020, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
        );

        SelectCourse.setFont(new java.awt.Font("宋体", 0, 24)); // NOI18N
        SelectCourse.setText("确定选课");
        SelectCourse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SelectCourseActionPerformed(evt);
            }
        });

        checkSelectedCourse.setFont(new java.awt.Font("宋体", 0, 24)); // NOI18N
        checkSelectedCourse.setText("查看已选课程");
        checkSelectedCourse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkSelectedCourseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(91, 91, 91)
                .addComponent(checkSelectedCourse)
                .addGap(162, 162, 162)
                .addComponent(SelectCourse, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(checkSelectedCourse, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
                    .addComponent(SelectCourse, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(36, 36, 36))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void SelectCourseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SelectCourseActionPerformed
        // TODO add your handling code here:
        int[] selectRows = jTable1.getSelectedRows();
        TableModel model = jTable1.getModel();
        final String filePath = "./data/"+UserService.getCurrentUser()+".txt";
        Student stu = StudentCourseOperation.readStuCourse();
       
        String repetitiveCourse ="请勿重复选课：";
        boolean flag = false;
        for (int i = 0; i < selectRows.length; i++) {
            String courseName = (String)model.getValueAt(selectRows[i], 0);
            String teacher = (String)model.getValueAt(selectRows[i], 1);
            int numSelected = (int)model.getValueAt(selectRows[i], 2)+1;
            int numOfstu = (int)model.getValueAt(selectRows[i], 3);
            
            if(!stu.add(new Course(courseName,teacher,numSelected,numOfstu,stu))){
                repetitiveCourse += courseName + System.lineSeparator();
                flag = true;
            }
        }
        if(flag) {
        	JOptionPane.showMessageDialog(null, repetitiveCourse);
        }
        
        StudentCourseOperation.writeStuCourse(filePath, stu);
//         try (OutputStream os = new FileOutputStream(FILE_PATH);
//             PrintWriter pw = new PrintWriter(os);) {
//            for (int i = 0; i < stu.getElective().size(); i++) {
//                pw.print(stu.getElective().get(i).getName() +" "+ stu.getElective().get(i).getTeacher() + " "+stu.getElective().get(i).getNumberSelected()+" "+stu.getElective().get(i).getNumberOfStudents()+System.getProperty("line.separator"));
//            }
//         } catch (Exception e) {
//            e.printStackTrace();
//         }
    }//GEN-LAST:event_SelectCourseActionPerformed

    private void checkSelectedCourseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSelectedCourseActionPerformed
        // TODO add your handling code here:
        Student stu = StudentCourseOperation.readStuCourse();
        String selectedCourse = new String();
        for(int i=0; i<stu.getElective().size();i++){
            selectedCourse += stu.getElective().get(i).getName() +" "+stu.getElective().get(i).getTeacher()+ System.lineSeparator();
        }
        JOptionPane.showMessageDialog(null, selectedCourse);
    }//GEN-LAST:event_checkSelectedCourseActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Student.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Student.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Student.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Student.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
        	@Override     public void run() {
                new StudentInterface().setVisible(true);
            }
        });
    }

   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton SelectCourse;
    private javax.swing.JButton checkSelectedCourse;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
